package com.jz.netthings.analysis.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.jz.netthings.analysis.bean.*;
import com.jz.netthings.analysis.mapper.DzJwdBaseMapper;
import com.jz.netthings.analysis.mapper.ProviderInfoDzjwdMapper;
import com.jz.netthings.analysis.mapper.VillagecolligateMapper;
import com.jz.netthings.analysis.service.ProviderInfoDzjwdService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jz.netthings.analysis.utils.AnalysisUtils;
import com.jz.netthings.appengine.baseData.ProviderInfo;
import com.jz.netthings.appengine.mapper.ProviderInfoMapper;
import com.jz.netthings.application.bodyCheck.bean.BodyCheck;
import com.jz.netthings.application.bodyCheck.mapper.mysql.BodyCheckMapper;
import com.jz.netthings.application.providerCollection.bean.ProviderCollection;
import com.jz.netthings.application.providerCollection.mapper.mysql.ProviderCollectionMapper;
import com.jz.netthings.application.providerReg.bean.ProviderReg;
import com.jz.netthings.application.providerReg.mapper.mysql.ProviderRegMapper;
import com.jz.netthings.bean.JwdEntity;
import com.jz.netthings.bloodsources.bean.XyLink;
import com.jz.netthings.bloodsources.mapper.XyLinkMapper;
import com.jz.netthings.exception.AdscmSystemException;
import com.jz.netthings.utils.AdscmBaseUtils;
import com.jz.netthings.utils.AdscmDateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yangyunyun
 * @since 2019-07-10
 */
@Service
public class ProviderInfoDzjwdServiceImpl extends ServiceImpl<ProviderInfoDzjwdMapper, ProviderInfoDzjwd> implements ProviderInfoDzjwdService {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    ProviderInfoMapper providerInfoMapper;
    @Autowired
    ProviderCollectionMapper providerCollectionMapper;
    @Autowired
    ProviderInfoDzjwdMapper providerInfoDzjwdMapper;
    @Autowired
    DzJwdBaseMapper dzJwdBaseMapper;
    @Autowired
    VillagecolligateMapper villagecolligateMapper;
    @Autowired
    ProviderRegMapper providerRegMapper;
    @Autowired
    BodyCheckMapper bodyCheckMapper;
    @Autowired
    XyLinkMapper xyLinkMapper;

    @Value("${jz.wd}")
    String jzWd;
    @Value("${jz.jd}")
    String jzJd;


    @Override
    public void loadBaseAddressDistance() throws AdscmSystemException {
        logger.info("开始计算距离...");
        Wrapper<DzJwdBase> wrapper = new EntityWrapper<>();
        wrapper.isNull("distance").or().eq("distance",0);
        List<DzJwdBase> jwdBaseList = dzJwdBaseMapper.selectList(wrapper);
        if (AdscmBaseUtils.getInstance().listIsNotEmpty(jwdBaseList)){
            for (DzJwdBase dzJwdBase : jwdBaseList) {
                Map<String, Integer> distance = AdscmBaseUtils.getInstance().getDistance(jzWd + "," + jzJd, dzJwdBase.getWd() + "," + dzJwdBase.getJd());
                dzJwdBase.setDistance(distance.get("distance"));
                dzJwdBase.setDuration(distance.get("duration"));
                logger.info("获取村落【"+dzJwdBase.getSplitAddress()+"】到浆站的距离及行车时间【"+distance+"】");
                dzJwdBaseMapper.updateById(dzJwdBase);
                try{
                    Thread.sleep(200);
                }catch (Exception e){}
            }
        }
    }

    @Override
    public void formatDz(String date) throws AdscmSystemException {
        logger.info("开始格式化浆员地址...");

        Wrapper<ProviderInfo> wrapper = new EntityWrapper<>();
        wrapper.gt("createDate",date);
        List<ProviderInfo> providerInfos = providerInfoMapper.selectList(wrapper);
        if (providerInfos != null && providerInfos.size()>0){
            for (ProviderInfo providerInfo : providerInfos) {
                logger.info("格式化浆员["+providerInfo.getId()+":"+providerInfo.getName()+"]地址["+providerInfo.getIdNoAddress()+"]");
                ProviderInfoDzjwd dzjwd = providerInfoDzjwdMapper.selectById(providerInfo.getId());
                boolean isInsert = false;
                if (dzjwd == null){
                    isInsert = true;
                    dzjwd = new ProviderInfoDzjwd();
                }
                dzjwd.setId(providerInfo.getId());
//                dzjwd.setCardId(providerInfo.getCardId());
                dzjwd.setIdNo(providerInfo.getIdNo());
                dzjwd.setName(providerInfo.getName());
                dzjwd.setIdNoAddress(providerInfo.getIdNoAddress());
                List<String> splitAddress = AnalysisUtils.splitAddress(providerInfo.getIdNoAddress());
                StringBuffer str = new StringBuffer();
                String dz = null;
                if (splitAddress != null && splitAddress.size()>0){
                    for (String address : splitAddress) {
                        str.append(address + "·");
                    }
                    if (str.length()>0){
                        dz = str.substring(0,str.length()-1);
                    }
                    String endAddress = dz.substring(dz.lastIndexOf("·")+1,dz.length());
                    int idx = dzjwd.getIdNoAddress().indexOf(endAddress);
                    endAddress = dzjwd.getIdNoAddress().substring(idx,dzjwd.getIdNoAddress().length());
                    dzjwd.setDetailVillage(endAddress);
                }
                dz = AnalysisUtils.addAddressBetweenStr(dz,"甘肃省","岷县","定西市");
                dzjwd.setSplitAddress(dz);
                if (isInsert){
                    providerInfoDzjwdMapper.insert(dzjwd);
                }else {
                    providerInfoDzjwdMapper.updateById(dzjwd);
                }
                //如果基本表中不存在这个地址，则获取
                DzJwdBase base = new DzJwdBase();
                base.setSplitAddress(dz);
                base = dzJwdBaseMapper.selectOne(base);
                if (base == null){
                    loadFormatDzJwdByAddress(dz);
                }
            }
            logger.info("格式化浆员地址完成...");

        }



    }

    @Override
    public void loadFormatDzJwdByAddress(String address)throws AdscmSystemException{
        logger.info("获取标准地址["+address+"]的经纬度...");
        if (AdscmBaseUtils.getInstance().isNotEmpty(address,null)){
            DzJwdBase base = new DzJwdBase();
            base.setSplitAddress(address);
            base = dzJwdBaseMapper.selectOne(base);
            boolean isInsert = false;
            if (base == null){
                isInsert = true;
                base = new DzJwdBase();
                base.setSplitAddress(address);
            }

            JwdEntity jwd = AdscmBaseUtils.getInstance().getJwdByAddress(address.replaceAll("·", ""));
            if (jwd != null){
                logger.info(jwd.toString());
                base.setJd(jwd.getJd());
                base.setWd(jwd.getWd());
                logger.info(base.toString());
                if (isInsert){
                    dzJwdBaseMapper.insert(base);
                }else {
                    dzJwdBaseMapper.updateById(base);
                }
            }

        }
    }


    @Override
    public void loadFormatDzJwd() throws AdscmSystemException {
        logger.info("获取标准地址的经纬度...");

        List<String> addressList = providerInfoDzjwdMapper.selectAllAddressDistinct();
        if (addressList != null && addressList.size()>0){
            logger.info("所有地址："+addressList.size());
            for (String address: addressList) {
                this.loadFormatDzJwdByAddress(address);
                try{
                    Thread.sleep(200);
                }catch (Exception e){}
            }
        }

    }


    @Override
    public List<DzJwdBase> getAllAddress() throws AdscmSystemException {
        logger.info("获取所有标准带有经纬度的地址...");

        return dzJwdBaseMapper.selectList(null);
    }

    @Override
    public Map<String, VillageAnalysisSupport> getAllPNumGroupByVillage() throws AdscmSystemException {
        logger.info("查询所有类型的地图统计综合数据...");
        Map<String, VillageAnalysisSupport> map = new HashMap<>();

        //查询类型：所有浆员
        VillageAnalysisSupport allProviderType = new VillageAnalysisSupport();
        allProviderType.setAnalysisType("allProvider");
        allProviderType.setAnalProCount(villagecolligateMapper.getAllProviderNum("allProviderNum"));
        allProviderType.setAnalysisDetail(dzJwdBaseMapper.selectDzJwdBaseAndDetails("allProviderNum"));
        map.put("allProvider",allProviderType);

        //今年已进站
        VillageAnalysisSupport currentYearComedType = new VillageAnalysisSupport();
        currentYearComedType.setAnalysisType("currentYearComed");
        currentYearComedType.setAnalProCount(villagecolligateMapper.getAllProviderNum("currentTimePNum"));
        currentYearComedType.setAnalysisDetail(dzJwdBaseMapper.selectDzJwdBaseAndDetails("currentTimePNum"));
        map.put("currentYearComed",currentYearComedType);

        //今年新浆员
        VillageAnalysisSupport currentYearAddType = new VillageAnalysisSupport();
        currentYearAddType.setAnalysisType("currentYearAddP");
        currentYearAddType.setAnalProCount(villagecolligateMapper.getAllProviderNum("currentTimeAddPNum"));
        currentYearAddType.setAnalysisDetail(dzJwdBaseMapper.selectDzJwdBaseAndDetails("currentTimeAddPNum"));
        map.put("currentYearAddP",currentYearAddType);

        //复苏浆员
        VillageAnalysisSupport fusuType = new VillageAnalysisSupport();
        fusuType.setAnalysisType("fusu");
        fusuType.setAnalProCount(villagecolligateMapper.getAllProviderNum("currentTimeFuSuPNum"));
        fusuType.setAnalysisDetail(dzJwdBaseMapper.selectDzJwdBaseAndDetails("currentTimeFuSuPNum"));
        map.put("fusu",fusuType);

        //忠诚浆员
        VillageAnalysisSupport zhongcType = new VillageAnalysisSupport();
        zhongcType.setAnalysisType("zhongc");
        zhongcType.setAnalProCount(villagecolligateMapper.getAllProviderNum("currentTimeZCPNum"));
        zhongcType.setAnalysisDetail(dzJwdBaseMapper.selectDzJwdBaseAndDetails("currentTimeZCPNum"));
        map.put("zhongc",zhongcType);

        //未链接浆员（后期补上）
        VillageAnalysisSupport notLianJType = new VillageAnalysisSupport();
        notLianJType.setAnalysisType("notLianJ");
        //已链接浆员总人数
        int connedPNum = villagecolligateMapper.getAllProviderNum("connedPNum");
        notLianJType.setAnalProCount(allProviderType.getAnalProCount() - connedPNum);
        notLianJType.setAnalysisDetail(dzJwdBaseMapper.selectDzJwdBaseAndDetails_1("(VILL.allProviderNum - VILL.connedPNum)"));
        map.put("notLianJ",notLianJType);


        //今年未进站
        VillageAnalysisSupport currentYearNotComedType = new VillageAnalysisSupport();
        currentYearNotComedType.setAnalysisType("currentYearNotComed");
        currentYearNotComedType.setAnalProCount(villagecolligateMapper.getAllProviderNum("currentTimeNotComedPNum"));
        currentYearNotComedType.setAnalysisDetail(dzJwdBaseMapper.selectDzJwdBaseAndDetails("currentTimeNotComedPNum"));
        map.put("currentYearNotComed",currentYearNotComedType);

        //休眠
        VillageAnalysisSupport xiuMianType = new VillageAnalysisSupport();
        xiuMianType.setAnalysisType("xiuMian");
        xiuMianType.setAnalProCount(villagecolligateMapper.getAllProviderNum("xiuMianPNum"));
        xiuMianType.setAnalysisDetail(dzJwdBaseMapper.selectDzJwdBaseAndDetails("xiuMianPNum"));
        map.put("xiuMian",xiuMianType);

        //流失
        VillageAnalysisSupport liuShiType = new VillageAnalysisSupport();
        liuShiType.setAnalysisType("liuShi");
        liuShiType.setAnalProCount(villagecolligateMapper.getAllProviderNum("liuShiPNum"));
        liuShiType.setAnalysisDetail(dzJwdBaseMapper.selectDzJwdBaseAndDetails("liuShiPNum"));
        map.put("liuShi",liuShiType);

        //已链接休眠的浆员
        VillageAnalysisSupport lianJieXiuMianType = new VillageAnalysisSupport();
        lianJieXiuMianType.setAnalysisType("lianJieXiuMian");
        lianJieXiuMianType.setAnalProCount(villagecolligateMapper.getAllProviderNum("connXMPNum"));
        lianJieXiuMianType.setAnalysisDetail(dzJwdBaseMapper.selectDzJwdBaseAndDetails("connXMPNum"));
        map.put("lianJieXiuMian",lianJieXiuMianType);

        //未链接休眠的浆员
        VillageAnalysisSupport notLianJieXiuMianType = new VillageAnalysisSupport();
        notLianJieXiuMianType.setAnalysisType("notLianJieXiuMian");
        notLianJieXiuMianType.setAnalProCount(villagecolligateMapper.getAllProviderNum("notConnXMPNum"));
        notLianJieXiuMianType.setAnalysisDetail(dzJwdBaseMapper.selectDzJwdBaseAndDetails("notConnXMPNum"));
        map.put("notLianJieXiuMian",notLianJieXiuMianType);

        return map;
    }

    @Override
    public Map<String, VillageAnalysisSupport> getAllPNumGroupByVillageByDate(String date) throws AdscmSystemException {

        logger.info("查询所有类型的地图统计综合数据...");
        Map<String, VillageAnalysisSupport> map = new HashMap<>();

        Date d = AdscmDateUtils.parseDate(date);
        date = AdscmDateUtils.getDateFormat(d);

        //查询类型：当天来登记的所有浆员
        VillageAnalysisSupport todayAllProvider = new VillageAnalysisSupport();
        todayAllProvider.setAnalysisType("todayAllProvider");

        Wrapper<ProviderReg> wrapper = new EntityWrapper<>();
        wrapper.between("regTime",date + " 00:00:00",date + " 23:59:59");
        Integer count = providerRegMapper.selectCount(wrapper);
        todayAllProvider.setAnalProCount(count);

        todayAllProvider.setAnalysisDetail(dzJwdBaseMapper.selectDzJwdBaseByRegDate(date + " 00:00:00",date + " 23:59:59"));
        map.put("todayAllProvider",todayAllProvider);



        //当天的积极浆员（在第一个登记到第一个体检这段时间内的）
        String minBodyCheckEndTime = this.getMinBodyCheckEndTime(date);
        VillageAnalysisSupport todayJijiProvider = new VillageAnalysisSupport();
        todayJijiProvider.setAnalysisType("todayJijiProvider");
        wrapper.between("regTime",date + " 00:00:00",minBodyCheckEndTime);
        count = providerRegMapper.selectCount(wrapper);
        todayJijiProvider.setAnalProCount(count);

        todayJijiProvider.setAnalysisDetail(dzJwdBaseMapper.selectDzJwdBaseByRegDate(date + " 00:00:00",minBodyCheckEndTime));
        map.put("todayJijiProvider",todayJijiProvider);

        //当天的新浆员
        VillageAnalysisSupport todayCreateProvider = new VillageAnalysisSupport();
        todayCreateProvider.setAnalysisType("todayCreateProvider");

        Wrapper<ProviderInfo> infoWrapper = new EntityWrapper<>();
        infoWrapper.between("createDate",date + " 00:00:00",date + " 23:59:59");
        count = providerInfoMapper.selectCount(infoWrapper);
        todayCreateProvider.setAnalProCount(count);

        todayCreateProvider.setAnalysisDetail(dzJwdBaseMapper.selectDzJwdBaseByCreateDate(date + " 00:00:00",date + " 23:59:59"));
        map.put("todayCreateProvider",todayCreateProvider);

        return map;
    }

    @Override
    public VillageColligate loadVillageDetailMsg(String villageName)throws AdscmSystemException{
        logger.info("装载村落【"+villageName+"】综合详细统计信息开始...");
        VillageColligate vc = null;
        if (AdscmBaseUtils.getInstance().isNotEmpty(villageName,null)){
            Wrapper<VillageColligate> wrapper = new EntityWrapper<>();
            wrapper.eq("villageName",villageName);
            List<VillageColligate> villageColligates = villagecolligateMapper.selectList(wrapper);
            if (villageColligates != null && villageColligates.size()>0){
                vc = villageColligates.get(0);
            }else{
                vc = new VillageColligate();
            }
        }else {
            throw new AdscmSystemException("参数为Null");
        }

        //查询村落注册浆员总人数
        long beginT = System.currentTimeMillis();
        long startT = System.currentTimeMillis();
        Wrapper<ProviderInfoDzjwd> wrapper = new EntityWrapper<>();
        wrapper.eq("splitAddress",villageName);
        int allProviderNum = providerInfoDzjwdMapper.selectCount(wrapper);
        long endT = System.currentTimeMillis();
        logger.info("查询村落注册浆员总人数耗时【"+(endT - startT)+"】毫秒，结果："+allProviderNum);
        startT = System.currentTimeMillis();
        //    private int currentTimePNum;//当期进站人数
        Date now = new Date();
        String nowStr = AdscmDateUtils.getNowOnlyDateFomat1(now);
        int nowYear = AdscmDateUtils.getTheYear(now);
        int currentTimePNum = providerInfoDzjwdMapper.selectCurrentTimePNum(villageName,nowYear + "-01-01 00:00:00",nowStr + " 23:59:59");
        endT = System.currentTimeMillis();
        logger.info("查询村落当期进站人数耗时【"+(endT - startT)+"】毫秒，结果："+currentTimePNum);
        startT = System.currentTimeMillis();
        //    private int currentTimeCollNum;//当期献浆量/袋
        int currentTimeCollNum = providerInfoDzjwdMapper.selectCurrentTimeCollNum(villageName,nowYear + "-01-01 00:00:00",nowStr + " 23:59:59");
        endT = System.currentTimeMillis();
        logger.info("查询村落当期献浆量/袋耗时【"+(endT - startT)+"】毫秒，结果："+currentTimeCollNum);
        startT = System.currentTimeMillis();

        //    private int lastTimePNum;//同期进站人数
        int lastYear = nowYear - 1;
        String lastTimeStr =AdscmDateUtils.getNowOnlyDateFomat1(now,-1);
        int lastTimePNum = providerInfoDzjwdMapper.selectCurrentTimePNum(villageName,lastYear + "-01-01 00:00:00",lastTimeStr + " 23:59:59");
        endT = System.currentTimeMillis();
        logger.info("查询村落同期进站人数耗时【"+(endT - startT)+"】毫秒，结果："+lastTimePNum);
        startT = System.currentTimeMillis();
        //    private int lastTimeCollNum;//同期献浆量/袋
        int lastTimeCollNum = providerInfoDzjwdMapper.selectCurrentTimeCollNum(villageName,lastYear + "-01-01 00:00:00",lastTimeStr + " 23:59:59");
        endT = System.currentTimeMillis();
        logger.info("查询村落同期献浆量/袋耗时【"+(endT - startT)+"】毫秒，结果："+lastTimeCollNum);
        startT = System.currentTimeMillis();
        //    private int collNumDiff;//当期浆量和同期献浆量的差
        int collNumDiff = currentTimeCollNum - lastTimeCollNum;

        //    private int lastYearCollNum;//去年献浆总量/袋
        int lastYearCollNum = providerInfoDzjwdMapper.selectCurrentTimeCollNum(villageName,lastYear + "-01-01 00:00:00",lastYear + "12-31 23:59:59");
        endT = System.currentTimeMillis();
        logger.info("查询村落去年献浆总量/袋耗时【"+(endT - startT)+"】毫秒，结果："+lastYearCollNum);
        startT = System.currentTimeMillis();

        vc.setVillageName(villageName);
        vc.setAllProviderNum(allProviderNum);
        vc.setCurrentTimePNum(currentTimePNum);
        vc.setCurrentTimeCollNum(currentTimeCollNum);
        vc.setLastTimePNum(lastTimePNum);
        vc.setLastTimeCollNum(lastTimeCollNum);
        vc.setCollNumDiff(collNumDiff);
        vc.setLastYearCollNum(lastYearCollNum);

        //    private int currentTimeAddPNum;//当期新增人数
        int currentTimeAddPNum = providerInfoDzjwdMapper.selectCurrentTimeAddPNum(villageName,nowYear + "-01-01 00:00:00",nowStr + " 23:59:59");
        endT = System.currentTimeMillis();
        logger.info("查询村落当期新增人数耗时【"+(endT - startT)+"】毫秒，结果："+currentTimeAddPNum);
        startT = System.currentTimeMillis();
        //    private int lastTimeAddPNum;//同期新增人数
        int lastTimeAddPNum = providerInfoDzjwdMapper.selectCurrentTimeAddPNum(villageName,lastYear + "-01-01 00:00:00",lastTimeStr + " 23:59:59");
        endT = System.currentTimeMillis();
        logger.info("查询村落同期新增人数耗时【"+(endT - startT)+"】毫秒，结果："+lastTimeAddPNum);
        startT = System.currentTimeMillis();
        //    private int currentTimeAddCollNum;//当期新增总浆量/袋
        int currentTimeAddCollNum = providerInfoDzjwdMapper.selectCurrentTimeAddCollNum(villageName,nowYear + "-01-01 00:00:00",nowStr + " 23:59:59");
        endT = System.currentTimeMillis();
        logger.info("查询村落当期新增总浆量/袋耗时【"+(endT - startT)+"】毫秒，结果："+currentTimeAddCollNum);
        startT = System.currentTimeMillis();

        //    private int lastTimeAddCollNum;//同期新增总浆量/袋
        int lastTimeAddCollNum = providerInfoDzjwdMapper.selectCurrentTimeAddCollNum(villageName,lastYear + "-01-01 00:00:00",lastTimeStr + " 23:59:59");
        endT = System.currentTimeMillis();
        logger.info("查询村落同期新增总浆量/袋耗时【"+(endT - startT)+"】毫秒，结果："+lastTimeAddCollNum);
        startT = System.currentTimeMillis();
        //    private int addNumDiff;//当期与同期新增人数差/人数
        int addNumDiff = currentTimeAddPNum - lastTimeAddPNum;


        vc.setCurrentTimeAddPNum(currentTimeAddPNum);
        vc.setLastTimeAddPNum(lastTimeAddPNum);
        vc.setCurrentTimeAddCollNum(currentTimeAddCollNum);
        vc.setLastTimeAddCollNum(lastTimeAddCollNum);
        vc.setAddNumDiff(addNumDiff);

        /**
         * 复苏浆员：头一年没来，第二年来了
         * 比如：
         *  当期复苏浆员：去年没来，今年当期来了
         *  同期复苏浆员：前年没来，去年同期来了
         */
        //    private int currentTimeFuSuPNum;//当期复苏献浆员总人数
        String beginTime1 = (nowYear - 1) + "-01-01 00:00:00";//开始时间1：当前年的前一年的开始
        String endTime1 = (nowYear - 1) + "-12-31 23:59:59";//开始时间1：当前年的前一年的结束

        String beginTime2 = nowYear + "-01-01 00:00:00";//开始时间2：当前年的开始时间
        String endTime2 = nowStr + " 23:59:59";//开始时间2：当前年的当前时间

        int currentTimeFuSuPNum = providerInfoDzjwdMapper.selectCurrentTimeFuSuPNum(villageName,beginTime1,endTime1,beginTime2,endTime2);//当期复苏献浆员总人数
        endT = System.currentTimeMillis();
        logger.info("查询村落当期复苏献浆员总人数耗时【"+(endT - startT)+"】毫秒，结果："+currentTimeFuSuPNum);
        startT = System.currentTimeMillis();
        //    private int currentTimeFuSuCollNum;//当期复苏浆员献浆总量/袋
        int currentTimeFuSuCollNum = providerInfoDzjwdMapper.selectCurrentTimeFuSuCollNum(villageName,beginTime1,endTime1,beginTime2,endTime2);//当期复苏浆员献浆总量/袋
        endT = System.currentTimeMillis();
        logger.info("查询村落当期复苏浆员献浆总量/袋耗时【"+(endT - startT)+"】毫秒，结果："+currentTimeFuSuCollNum);
        startT = System.currentTimeMillis();

        beginTime1 = (nowYear - 2) + "-01-01 00:00:00";//开始时间1：去年的前一年的开始
        endTime1 = (nowYear - 2) + "-12-31 23:59:59";//开始时间1：去年的前一年的结束

        beginTime2 = nowYear + "-01-01 00:00:00";//开始时间2：去年的开始时间
        endTime2 = nowStr + " 23:59:59";//开始时间2：去年的当前时间


        //    private int lastTimeFuSuNum;//同期复苏浆员总人数lastTimePNum-lastTimeAddPNum-lastTimeZCPNum
        int lastTimeFuSuNum = providerInfoDzjwdMapper.selectCurrentTimeFuSuPNum(villageName,beginTime1,endTime1,beginTime2,endTime2);//同期复苏浆员总人数lastTimePNum-lastTimeAddPNum-lastTimeZCPNum
        endT = System.currentTimeMillis();
        logger.info("查询村落同期复苏浆员总人数耗时【"+(endT - startT)+"】毫秒，结果："+lastTimeFuSuNum);
        startT = System.currentTimeMillis();

        //    private int lastTimeFuSuCollNum;//同期复苏浆员浆量   lastTimeCollNum-lastTimeAddCollNum-lastTimeZCCollNum
        int lastTimeFuSuCollNum = providerInfoDzjwdMapper.selectCurrentTimeFuSuCollNum(villageName,beginTime1,endTime1,beginTime2,endTime2);//同期复苏浆员浆量   lastTimeCollNum-lastTimeAddCollNum-lastTimeZCCollNum
        endT = System.currentTimeMillis();
        logger.info("查询村落同期复苏浆员浆量耗时【"+(endT - startT)+"】毫秒，结果："+lastTimeFuSuCollNum);
        startT = System.currentTimeMillis();

        vc.setCurrentTimeFuSuPNum(currentTimeFuSuPNum);
        vc.setCurrentTimeFuSuCollNum(currentTimeFuSuCollNum);
        vc.setLastTimeFuSuNum(lastTimeFuSuNum);
        vc.setLastTimeFuSuCollNum(lastTimeFuSuCollNum);


        /**
         * 忠诚浆员：连续两年都来了
         * 比如：
         *  当期忠诚浆员：去年来了，今年当期也来了
         *  同期忠诚浆员：前年来了，去年同期也来了
         */

        beginTime1 = (nowYear - 1) + "-01-01 00:00:00";//开始时间1：去年的开始
        endTime1 = (nowYear - 1) + "-12-31 23:59:59";//开始时间1：去年的结束

        beginTime2 = nowYear + "-01-01 00:00:00";//开始时间2：今年的开始
        endTime2 = nowStr + " 23:59:59";//开始时间2：今年的当前时间

        // int currentTimeZCPNum;//当期忠诚献浆员总人数
        int currentTimeZCPNum = providerInfoDzjwdMapper.selectCurrentTimeZCPNum(villageName,beginTime1,endTime1,beginTime2,endTime2);
        endT = System.currentTimeMillis();
        logger.info("查询村落忠诚献浆员当期总人数耗时【"+(endT - startT)+"】毫秒，结果："+currentTimeZCPNum);
        startT = System.currentTimeMillis();

        // int currentTimeZCCollNum;//当期忠诚献浆员献浆总量
        int currentTimeZCCollNum = providerInfoDzjwdMapper.selectCurrentTimeZCCollNum(villageName,beginTime1,endTime1,beginTime2,endTime2);
        endT = System.currentTimeMillis();
        logger.info("查询村落忠诚献浆员当期献浆总量耗时【"+(endT - startT)+"】毫秒，结果："+currentTimeZCCollNum);
        startT = System.currentTimeMillis();

        // int lastYearZCCollNum;//忠诚浆员去年全年献浆量
        int lastYearZCCollNum = providerInfoDzjwdMapper.selectTimeZCCollNum(villageName,beginTime1,endTime1,beginTime2,endTime2,beginTime1,endTime1);
        endT = System.currentTimeMillis();
        logger.info("查询村落忠诚浆员去年全年献浆量耗时【"+(endT - startT)+"】毫秒，结果："+lastYearZCCollNum);
        startT = System.currentTimeMillis();


        beginTime1 = (nowYear - 2) + "-01-01 00:00:00";//开始时间1：前年的开始
        endTime1 = (nowYear - 2) + "-12-31 23:59:59";//开始时间1：前年的结束

        beginTime2 = (nowYear - 1) + "-01-01 00:00:00";//开始时间2：去年的开始
        endTime2 = lastTimeStr + " 23:59:59";//开始时间2：去年的当前时间
        // int lastTimeZCPNum;//同期忠诚献浆员总人数
        int lastTimeZCPNum = providerInfoDzjwdMapper.selectCurrentTimeZCPNum(villageName,beginTime1,endTime1,beginTime2,endTime2);
        endT = System.currentTimeMillis();
        logger.info("查询村落忠诚献浆员同期期总人数耗时【"+(endT - startT)+"】毫秒，结果："+lastTimeZCPNum);
        startT = System.currentTimeMillis();


        // int lastTimeZCCollNum;//同期忠诚献浆员献浆总量
        int lastTimeZCCollNum = providerInfoDzjwdMapper.selectCurrentTimeZCCollNum(villageName,beginTime1,endTime1,beginTime2,endTime2);
        endT = System.currentTimeMillis();
        logger.info("查询村落忠诚献浆员同期献浆总量耗时【"+(endT - startT)+"】毫秒，结果："+lastTimeZCCollNum);
        startT = System.currentTimeMillis();



        // int zcCollNumDiff;//当期与同期忠诚浆员浆量差/袋
        int zcCollNumDiff = currentTimeZCCollNum - lastTimeZCCollNum;

        vc.setCurrentTimeZCPNum(currentTimeZCPNum);
        vc.setCurrentTimeZCCollNum(currentTimeZCCollNum);
        vc.setLastTimeZCPNum(lastTimeZCPNum);
        vc.setLastTimeZCCollNum(lastTimeZCCollNum);
        vc.setZcCollNumDiff(zcCollNumDiff);
        vc.setLastYearZCCollNum(lastYearZCCollNum);






        // int currentTimeNotComedPNum;//当期未进站总人数
        int currentTimeNotComedPNum = providerInfoDzjwdMapper.selectCurrentTimeNotComedPNum(villageName,nowYear + "-01-01 00:00:00",nowStr + " 23:59:59");//当期未进站总人数
        endT = System.currentTimeMillis();
        logger.info("查询村落当期未进站总人数耗时【"+(endT - startT)+"】毫秒，结果："+currentTimeNotComedPNum);
        startT = System.currentTimeMillis();


        beginTime1 = (nowYear - 1) + "-01-01 00:00:00";//开始时间1：去年的开始
        endTime1 = (nowYear - 1) + "-12-31 23:59:59";//开始时间1：去年的结束

        beginTime2 = nowYear + "-01-01 00:00:00";//开始时间2：今年的开始
        endTime2 = nowStr + " 23:59:59";//开始时间2：今年的当前时间
        // int currentTimeNotComedPLastYearCollNum;//当期未进站总人数去年献浆总量袋
        int currentTimeNotComedPLastYearCollNum = providerInfoDzjwdMapper.selectCurrentTimeNotComedPLastYearCollNum(villageName,beginTime1,endTime1,beginTime2,endTime2);
        endT = System.currentTimeMillis();
        logger.info("查询村落当期未进站总人数去年献浆总量袋耗时【"+(endT - startT)+"】毫秒，结果："+currentTimeNotComedPLastYearCollNum);
        startT = System.currentTimeMillis();

        vc.setCurrentTimeNotComedPNum(currentTimeNotComedPNum);
        vc.setCurrentTimeNotComedPLastYearCollNum(currentTimeNotComedPLastYearCollNum);

        /**
         * 休眠浆员：去年来了，今年没来
         * 流失浆员：连续两年都没来了
         */
        //int xiuMianPNum;//休眠浆员总人数
        beginTime1 = (nowYear - 1) + "-01-01 00:00:00";//开始时间1：去年的开始
        endTime1 = (nowYear - 1) + "-12-31 23:59:59";//开始时间1：去年的结束

        beginTime2 = nowYear + "-01-01 00:00:00";//开始时间2：今年的开始
        endTime2 = nowStr + " 23:59:59";//开始时间2：今年的当前时间
        int xiuMianPNum = providerInfoDzjwdMapper.selectXiuMianPNum(villageName,beginTime1,endTime1,beginTime2,endTime2);
        //休眠浆员ID集合
        List<Long> xiuMianProviderNo = providerInfoDzjwdMapper.selectXiuMianProviderNo(villageName,beginTime1,endTime1,beginTime2,endTime2);
        endT = System.currentTimeMillis();
        logger.info("查询村落休眠浆员总人数耗时【"+(endT - startT)+"】毫秒，结果："+xiuMianPNum);
        startT = System.currentTimeMillis();

        //int lastYearXiuMianCollNum;//休眠浆员去年献浆总量/袋
        int lastYearXiuMianCollNum = providerInfoDzjwdMapper.selectLastYearXiuMianCollNum(villageName,beginTime1,endTime1,beginTime2,endTime2);
        endT = System.currentTimeMillis();
        logger.info("查询村落休眠浆员去年献浆总量/袋耗时【"+(endT - startT)+"】毫秒，结果："+lastYearXiuMianCollNum);
        startT = System.currentTimeMillis();

        endTime1 = lastTimeStr + " 23:59:59";//开始时间1：去年的结束
        //int lastTimeXiuMianCollNum;//休眠浆员同期献浆总量/袋
        int lastTimeXiuMianCollNum = providerInfoDzjwdMapper.selectLastYearXiuMianCollNum(villageName,beginTime1,endTime1,beginTime2,endTime2);
        endT = System.currentTimeMillis();
        logger.info("查询村落休眠浆员同期献浆总量/袋耗时【"+(endT - startT)+"】毫秒，结果："+lastTimeXiuMianCollNum);
        startT = System.currentTimeMillis();

        vc.setXiuMianPNum(xiuMianPNum);
        vc.setLastYearXiuMianCollNum(lastYearXiuMianCollNum);
        vc.setLastTimeXiuMianCollNum(lastTimeXiuMianCollNum);


        //int liuShiPNum;//流失浆员总人数
        beginTime1 = (nowYear - 1) + "-01-01 00:00:00";//开始时间：去年的开始
        endTime1 = nowStr + " 23:59:59";//开始时间：今年的当前时间
        int liuShiPNum = providerInfoDzjwdMapper.selectCurrentTimeNotComedPNum(villageName,beginTime1,endTime1);
        endT = System.currentTimeMillis();
        logger.info("查询村落流失浆员总人数耗时【"+(endT - startT)+"】毫秒，结果："+liuShiPNum);
        startT = System.currentTimeMillis();
        vc.setLiuShiPNum(liuShiPNum);


        //已链接献浆员总人数
        int connedPNum = xyLinkMapper.selectCount(null);

        Wrapper<XyLink> linkWrapper = new EntityWrapper<>();
        linkWrapper.in("linkProviderId",xiuMianProviderNo);
        linkWrapper.setSqlSelect("linkProviderId");
        List<XyLink> xyLinks = xyLinkMapper.selectList(linkWrapper);
        //已链接休眠的献浆员
        int connXMPNum = xyLinks.size();

        List<Long> xiuMianLinksPNo = new ArrayList<>();
        if (connXMPNum > 0){
            for (XyLink link : xyLinks){
                xiuMianLinksPNo.add(link.getLinkProviderId());
            }
        }
        Wrapper<ProviderCollection> collWrapper = null;
        int lastTimeConnXMCollNum = 0;
        if (AdscmBaseUtils.getInstance().listIsNotEmpty(xiuMianLinksPNo)){

            beginTime2 = (nowYear - 1) + "-01-01 00:00:00";//开始时间2：去年的开始
            endTime2 = lastTimeStr + " 23:59:59";//开始时间2：去年的当前时间
            collWrapper = loadCollWrapper(xiuMianLinksPNo,beginTime2,endTime2);

            //已链接休眠的献浆员同期献浆总量/袋
            lastTimeConnXMCollNum = providerCollectionMapper.selectCount(collWrapper);
        }


        endT = System.currentTimeMillis();
        logger.info("查询已链接休眠的献浆员同期献浆总量/袋耗时【"+(endT - startT)+"】毫秒，结果："+lastTimeConnXMCollNum);
        startT = System.currentTimeMillis();

        vc.setConnedPNum(connedPNum);
        vc.setConnXMPNum(connXMPNum);
        vc.setLastTimeXiuMianCollNum(lastTimeXiuMianCollNum);


        int notConnXMPNum = xiuMianProviderNo.size() - connXMPNum;//休眠中未链接献浆员
        //休眠中未链接的浆员
        List<Long> xiuMianNotLinkPNo = (List<Long>)AdscmBaseUtils.getInstance().removeList(xiuMianProviderNo, xiuMianLinksPNo);
        beginTime2 = (nowYear - 1) + "-01-01 00:00:00";//开始时间2：去年的开始
        endTime2 = lastTimeStr + " 23:59:59";//开始时间2：去年的当前时间
        collWrapper = loadCollWrapper(xiuMianNotLinkPNo,beginTime2,endTime2);
        //休眠中未链接献浆员同期献浆总量/袋
        int lastTimeNotConnXMCollNum = providerCollectionMapper.selectCount(collWrapper);
        endT = System.currentTimeMillis();
        logger.info("查询休眠中未链接献浆员同期献浆总量/袋耗时【"+(endT - startT)+"】毫秒，结果："+lastTimeNotConnXMCollNum);
        startT = System.currentTimeMillis();

        vc.setNotConnXMPNum(notConnXMPNum);
        vc.setLastTimeNotConnXMCollNum(lastTimeNotConnXMCollNum);


        List<Map<String, Long>> linkNurseMaps = providerInfoDzjwdMapper.selectLinkNurseYgCount(villageName);
        if (AdscmBaseUtils.getInstance().listIsNotEmpty(linkNurseMaps)){
            Map<String, Long> temp = linkNurseMaps.get(0);
            Long connNurseNum = temp.get("NURSECOUNT");//管理护士总人数
            Long volunteerNum = temp.get("VOLUNTEECOUNT");//义工总人数
            Long volunConnGJZNum = temp.get("LINKVOLUNTEECOUNT");//义工管理浆员总人数

            endT = System.currentTimeMillis();
            logger.info("查询管理护士总人数、义工总人数、义工管理浆员总人数 耗时【"+(endT - startT)+"】毫秒，结果：【connNurseNum："+connNurseNum+"，volunteerNum："+volunteerNum+"，volunConnGJZNum："+volunConnGJZNum+"】");
            startT = System.currentTimeMillis();

            vc.setConnNurseNum(connNurseNum.intValue());
            vc.setVolunteerNum(volunteerNum.intValue());
            vc.setVolunConnGJZNum(volunConnGJZNum.intValue());
        }

        beginTime1 = nowYear + "-01-01 00:00:00";//开始时间1：当前年的前一年的开始
        endTime1 = nowYear + "-12-31 23:59:59";//开始时间1：当前年的前一年的结束
        List<Long> comedNotLinkList = providerInfoDzjwdMapper.selectComedNotLink(villageName, beginTime1, endTime1);

        int comedNotConnPNum = comedNotLinkList.size();//今年已进站但未被链接的浆员
        int comedNotConnThisTimeCollNum = 0;
        int comedNotConnLastTimeCollNum = 0;
        int comedNotConnLastYearCollNum = 0;
        if(comedNotConnPNum > 0){

            collWrapper = loadCollWrapper(comedNotLinkList,beginTime1,endTime1);
            comedNotConnThisTimeCollNum = providerCollectionMapper.selectCount(collWrapper);//今年已进站未链接浆员当期献浆量

            endT = System.currentTimeMillis();
            logger.info("查询今年已进站但未被链接的浆员 耗时【"+(endT - startT)+"】毫秒，结果："+ comedNotConnThisTimeCollNum);
            startT = System.currentTimeMillis();

            beginTime1 = (nowYear - 1) + "-01-01 00:00:00";//开始时间1：当前年的前一年的开始
            endTime1 = lastTimeStr + " 23:59:59";//开始时间1：当前年的前一年同期的结束
            collWrapper = loadCollWrapper(comedNotLinkList,beginTime1,endTime1);
            comedNotConnLastTimeCollNum = providerCollectionMapper.selectCount(collWrapper);//今年已进站未链接浆员同期献浆量

            endT = System.currentTimeMillis();
            logger.info("查询今年已进站未链接浆员同期献浆量 耗时【"+(endT - startT)+"】毫秒，结果："+ comedNotConnLastTimeCollNum);
            startT = System.currentTimeMillis();

            beginTime1 = (nowYear - 1) + "-01-01 00:00:00";//开始时间1：当前年的前一年的开始
            endTime1 = (nowYear - 1) + "-12-31 23:59:59";//开始时间1：当前年的前一年的结束
            collWrapper = loadCollWrapper(comedNotLinkList,beginTime1,endTime1);
            comedNotConnLastYearCollNum = providerCollectionMapper.selectCount(collWrapper);//今年已进站未链接浆员去年献浆总量
        }

        endT = System.currentTimeMillis();
        logger.info("查询今年已进站未链接浆员去年献浆总量 耗时【"+(endT - startT)+"】毫秒，结果："+ comedNotConnLastYearCollNum);

        vc.setComedNotConnPNum(comedNotConnPNum);
        vc.setComedNotConnThisTimeCollNum(comedNotConnThisTimeCollNum);
        vc.setComedNotConnLastTimeCollNum(comedNotConnLastTimeCollNum);
        vc.setComedNotConnLastYearCollNum(comedNotConnLastYearCollNum);

        logger.info("总耗时【"+(endT - beginT)+"】毫秒");

        return vc;

    }


    @Override
    public void loadAllVillageDetailMsg(String villageName) throws AdscmSystemException {
        logger.info("装载指定或所有标准村落地址的详细统计信息...");
        long beginTime = System.currentTimeMillis();

        if (AdscmBaseUtils.getInstance().isNotEmpty(villageName,null)){
            VillageColligate villageColligate = this.loadVillageDetailMsg(villageName);
            insertOrUpdateVill(villageColligate);
        }else {
            List<DzJwdBase> list = dzJwdBaseMapper.selectList(null);
            for (DzJwdBase dzJwdBase : list) {
                VillageColligate villageColligate = this.loadVillageDetailMsg(dzJwdBase.getSplitAddress());
                insertOrUpdateVill(villageColligate);
            }
        }
        long endTime = System.currentTimeMillis();
        logger.info("装载完成，耗时【"+((endTime - beginTime)/1000)+"】秒");
    }

    /**
     * 增加或更新
     * @param villageColligate
     */
    private void insertOrUpdateVill(VillageColligate villageColligate){
        if (villageColligate != null && villageColligate.getId() != null && villageColligate.getId()>0){
            villagecolligateMapper.updateById(villageColligate);
        }else {
            villagecolligateMapper.insert(villageColligate);
        }
    }

    /**
     * 得到某一天的体检的最快结束时间
     * @param date
     * @return
     */
    @Override
    public String getMinBodyCheckEndTime(String date){
        String minBodyCheckEndTime = bodyCheckMapper.getMinBodyCheckEndTime(date + " 00:00:00",date + " 23:59:59");
        if (!AdscmBaseUtils.getInstance().isNotEmpty(minBodyCheckEndTime,null)){
            //如果为null，则用第一个登记时间 + 30min
            String minRegTime = providerRegMapper.getMinRegTime(date + " 00:00:00", date + " 23:59:59");
            if(AdscmBaseUtils.getInstance().isNotEmpty(minBodyCheckEndTime,null)){
                Date minRegDateTime = AdscmDateUtils.parseDateL(minRegTime);
                minBodyCheckEndTime = AdscmDateUtils.getNowOnlyDateFomat2(minRegDateTime, 30, Calendar.MINUTE);
            }else {
                minBodyCheckEndTime = date + " 00:00:00";
            }
        }
        return minBodyCheckEndTime;
    }


    @Override
    public List<RegisterGtt> getGttByDateVillage(String villageName, String date, boolean isNew,boolean isPositive) throws AdscmSystemException {
        logger.info("查询村落【"+villageName+"】【"+date+"】的浆员进站甘特图...");

        String beginTime = date + " 00:00:00";
        String endTime = date + " 23:59:59";
        if (!isNew){
            if (isPositive){
                //当天的积极浆员（在第一个登记到第一个体检这段时间内的）
                endTime = this.getMinBodyCheckEndTime(date);
            }
        }
        List<RegisterGtt> gttList = providerInfoDzjwdMapper.selectRegGttList(villageName,beginTime, endTime,(isNew ? "1":"0"));

        if (gttList != null && gttList.size()>0){
            for (RegisterGtt gtt : gttList) {
                Wrapper<ProviderCollection> wrapper = new EntityWrapper<>();
                wrapper.eq("registerNo",gtt.getRegisterNo());
                wrapper.eq("providerNo",gtt.getProviderId());
                List<ProviderCollection> list = providerCollectionMapper.selectList(wrapper);
                boolean isEnd = false;
                if (list != null && list.size()>0){
                    ProviderCollection coll = list.get(0);
                    Date endTime1 = coll.getEndTime();
                    if (endTime1 != null){
                        endTime = AdscmDateUtils.getDateFomat(endTime1);
                        gtt.setEndTime(endTime);
                        gtt.setIsEnd("1");
                        isEnd = true;
                    }
                }
                if (!isEnd){
                    boolean sameDay = AdscmDateUtils.isSameDay(AdscmDateUtils.parseDate(date), new Date());
                    if(sameDay){
                        endTime = AdscmDateUtils.getDateFomat(new Date());
                    }else {
                        endTime = date + " 18:00:00";
                    }

                    gtt.setEndTime(endTime);
                    gtt.setIsEnd("0");
                }
                try {
                    long between = AdscmDateUtils.betweenMinutes(gtt.getStartTime(),endTime);
                    gtt.setBetweenMinutes(between+"");
                } catch (Exception e) {}
                boolean sameDay = AdscmDateUtils.isSameDay(AdscmDateUtils.parseDate(gtt.getCreateDate()),AdscmDateUtils.parseDate(gtt.getStartTime()));
                gtt.setIsNew(sameDay ? "1":"0");

                if("1".equals(gtt.getGender())){
                    gtt.setGender("男");
                }else {
                    gtt.setGender("女");
                }
            }
        }
        return gttList;
    }

    @Override
    public VillageColligate getVillageDetailMsg(String villageName) throws AdscmSystemException {

        logger.info("查询村落【"+villageName+"】的综合统计信息...");
        Wrapper<VillageColligate> wrapper = new EntityWrapper<>();
        wrapper.eq("villageName",villageName);
        List<VillageColligate> list = villagecolligateMapper.selectList(wrapper);
        if (list != null && list.size()>0){
            return list.get(0);
        }
        return new VillageColligate();
    }


    private Wrapper<ProviderCollection> loadCollWrapper(List<Long> providerNoList,String beginTime,String endTime){
        Wrapper<ProviderCollection> collWrapper = new EntityWrapper<>();
        collWrapper.setSqlSelect("registerNo");
        collWrapper.in("providerNo",providerNoList);
        collWrapper.ge("totalPlasmaNum",590);
        collWrapper.eq("isDeal",1);
        collWrapper.between("collectionDate",beginTime,endTime);
        return collWrapper;
    }
}
